<template>
  <div id="ReportRulesSpecial">

    <Splitpanes horizontal class="horizontalLine">
      <Pane size="55">
        <vxe-toolbar perfect>
          <template #buttons>
            <vxe-input v-model="form.searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询"
              @keyup="keyupEnter" @clear="findReportRulesSpecial" @search-click="findReportRulesSpecial()"></vxe-input>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="iloading"
              @click="findReportRulesSpecial"></vxe-button>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新增"
              @click="handleAdd"></vxe-button>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="保存" @click="handleSave"
              :loading="saveLoading"></vxe-button>
            <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除"
              @click="handleDelete"></vxe-button>
          </template>
        </vxe-toolbar>
        <div class="tableBox">
          <vxe-table ref="reportTable" v-loading="loading" class="mytable-scrollbar"
            :row-config="{ isCurrent: true, isHover: true }" :data="rulesList" border style="width: 100%" height="auto"
            :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }" @current-change="rowClick" resizable
            show-overflow keep-source :column-config="{ resizable: true }">
            <vxe-column type="checkbox" width="50"></vxe-column>
            <vxe-column field="priorityLevel" title="优先级" width="80" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #default="{ row }">
                <div>{{ row.priorityLevel }}</div>
              </template>
              <template #edit="{ row, rowIndex }">
                <vxe-input v-model="row.priorityLevel" placeholder="请输入优先级" style="width: 100%"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="code" title="编码" width="90" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #default="{ row }">
                <div>{{ row.code }}</div>
              </template>
              <template #edit="{ row, rowIndex }">
                <vxe-input v-model="row.code" placeholder="请输入编码" style="width: 100%"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="name" title="名称" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #default="{ row }">
                <div>{{ row.name }}</div>
              </template>
              <template #edit="{ row, rowIndex }">
                <vxe-input v-model="row.name" placeholder="请输入名称" style="width: 100%"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="reportId" title="报告模板" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #edit="{ row, rowIndex }">
                <SelectDataGrid :url="'/api/pubReport/getReportByCommonId'" :column="[
                  { field: 'code', title: '编号' }, //列标题
                  { field: 'name', title: '名称' }
                ]" :searchParam="{ commonId: dataForm.commonId }"
                  @SelectCellClick="(e) => { SelectRowClick(e, rowIndex); }">
                </SelectDataGrid>
                <!-- <div style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap" v-else>
                  {{ row.reportName }}
                </div> -->
              </template>
              <template #default="{ row }">
                {{ row.reportName }}
              </template>
              <!-- <template #default="{ row }">
                <div>{{ row.reportId }}</div>
              </template>
              <template #edit="{ row, rowIndex }"> -->
              <!-- <vxe-input v-model="row.reportId" placeholder="报告模板" style="width: 100%"></vxe-input> -->

              <!-- <VxePulldownSelectionReport ref="VxePulldownSelectionReport2" v-enterNextInput :isChild="false"
                :sourceMark="2" :url="'/api/pubReport/getReportByCommonId'" :dataObj="commonIdData"
                @focusEvent="focusEvent(2)" @selectedSaveValue="selectedSaveValue" @confirmClick="selectchange2"
                :tableColumn="[
                  { field: 'code', title: '编码', width: '100px' },
                  { field: 'name', title: '名称' },
                  { field: 'rptGroups', title: '被那些报告单元应用' }
                ]"
                :aimKeys="[{ targetField: 'reportId', sourceField: 'id' }, { targetField: 'report', sourceField: 'entity' }]"
                :displayTexts="['name']" :displayTextObj="form.reportName2 ? form.reportName2 : ''" /> -->
              <!-- </template> -->
            </vxe-column>
            <vxe-column field="describe" title="条件描述" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #default="{ row }">
                <div>{{ row.describe }}</div>
              </template>
              <template #edit="{ row, rowIndex }">
                <vxe-input v-model="row.describe" style="width: 100%"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="isUse" width="90" title="是否启用">
              <template #default="{ row }">
                <vxe-switch v-model="row.isUse" size="mini" open-label="是" close-label="否" open-value="1"
                  close-value="0"></vxe-switch>
              </template>
            </vxe-column>
            <vxe-column field="rules" title="条件" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #default="{ row }">
                <div>{{ row.rules }}</div>
              </template>
              <template #edit="{ row, rowIndex }">
                <vxe-input v-model="row.rules" style="width: 100%"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="referList" title="规则中设置数据" :visible="false"></vxe-column>
            <vxe-column field="selectValue" title="选中的规则" :visible="false"></vxe-column>
          </vxe-table>
        </div>
      </Pane>
      <Pane size="45">
        <div class="toolbartitle">规则设置</div>
        <div class="tableBox">
          <formulaTools ref="referFormRef" @repressChange="getRefer" />
        </div>
      </Pane>
    </Splitpanes>
  </div>
</template>
<script setup lang="ts">

// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, watch, onMounted } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';
import { pageSizes, notifyType, notifyMessage, IsEmpty } from '../../utils/common';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { VxeTablePropTypes } from 'vxe-table';
import { ElMessage } from 'element-plus';
import 'splitpanes/dist/splitpanes.css';
import { VXETable } from 'vxe-table';
import XEUtils from 'xe-utils';
import { AppStore } from '../../stores/store';
import axios from 'axios';
import ReportRulesSpecial from './ReportRulesSpecial.vue'; //仪器报表
import ReportAttribute from './ReportAttribute.vue'; //属性设置
import formulaTools from '@/components/FormulaToolsBak.vue';
import { Document, Menu as IconMenu, Location, Setting } from '@element-plus/icons-vue';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import SelectDataGrid from '@/components/SelectDataGrid.vue';
import VxePulldownSelectionReport from '../../components/VxePulldownSelectionReport.vue';


// 全局变量定义区 ==========
// 公共组件标题
const content = ref('报告规则设置');

let referFormRef: any = ref(null); //规则回显数据
let referForm = {
  selectValue: '',
  referList: '',
  rptGroup: ''
};
let rowdata = {}; //点击当前行的数据

let iloading = ref(false);//刷新图标

let saveLoading = ref(false);//保存图标

// 页面加载时更新用户列表
let loading = ref(false);

let rowIndexClick = 0; //点击当前行下标

//获取当前点击的菜单Id
let commonIdData = reactive({
  commonId: ''
});

let { proxy }: any = getCurrentInstance();

let dataForm: any = reactive({
  reportGroupId: '',
  rptGroup: '',
  reportGroupName: '',
  commonId: ''
});

let form = reactive({
  searchValue: ''
});

let rulesList: any = reactive([]); //报表列表

let reportTable = ref();

// 条数/页
const PageSizeList = [10, 50, 100, 200, 500];

let page = reactive({
  currentPage: 1,
  pageSize: PageSizeList[1],
  totalResult: 0
});

const editableContent = ref(null);
let orgaList: any = reactive([]);//组织机构列表


// 方法定义区 =============

//暴露方法,供父组件调用
defineExpose({ initPageInfo });

// onMounted(() => {
//   findReportRulesSpecial();
// });

function initPageInfo(reqData: any) {
  dataForm.reportGroupId = reqData.reportGroupId;
  dataForm.rptGroup = reqData.rptGroup;
  dataForm.reportGroupName = reqData.reportGroupName;
  dataForm.commonId = reqData.commonId;
  findReportRulesSpecial();
}

//根据报告单元查询特殊规则
function findReportRulesSpecial() {
  loading.value = true;
  iloading.value = true;
  rulesList.length = 0;
  const url = '/api/pub/getReportRuleListByGroupId';

  proxy.$http
    .get(url, { params: { reportGroupId: dataForm.reportGroupId, rptGroup: dataForm.rptGroup, keywords: form.searchValue } })
    .then((res: any) => {
      if (res.data) {
        if (!IsEmpty(res.data) && res.data) {
          rulesList.push(...res.data);
          if (rulesList.length > 0) {
            rowClick({
              row: rulesList[0],
              rowIndex: 0
            });
          } else {
            referForm.referList = '';
            referForm.selectValue = '';
            referForm.rptGroup = dataForm.rptGroup;
            referFormRef.value.initReferForm(referForm);
          }
        }
      }
      loading.value = false;
      iloading.value = false;
    })
    .catch((err: any) => {
      loading.value = false;
      iloading.value = false;
      VxeMessage('查询报告项目结果失败', VxeNotifyType.error);
    });
}

// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findReportRulesSpecial();
  }
}


// 点击新增
function handleAdd() {
  clearFormAndobj();
}


function clearFormAndobj() {
  rulesList.push({
    id: '',
    code: '',
    name: '',
    describe: '',
    type: '1',
    reportId: '',
    rules: '',
    reportGroupId: dataForm.reportGroupId,
    rptGroup: dataForm.rptGroup,
    priorityLevel: '',
    isUse: '1',
    isSplit: '',
    ruleType: '5'//2024-12-12将ruleType值设置为5
  });
}


//规则组件返回值
function getRefer(referTab: any) {
  // 实时插入点击的规则当前行中
  if (rulesList.length > 0) {
    rulesList[rowIndexClick].referList = IsEmpty(JSON.stringify(referTab.tab)) ? '' : JSON.stringify(referTab.tab);
    rulesList[rowIndexClick].referDataList = IsEmpty(referTab.tab) ? null : referTab.tab;
    rulesList[rowIndexClick].rules = IsEmpty(referTab.sqlExpress) ? '' : referTab.sqlExpress;
    rulesList[rowIndexClick].selectValue = IsEmpty(JSON.stringify(referTab.selectValue)) ? '' : JSON.stringify(referTab.selectValue);
    rulesList[rowIndexClick].describe = IsEmpty(referTab.factorDescribe) ? '' : referTab.factorDescribe;
  }
}

// 表格点击当前行
function rowClick({ row, rowIndex }: any) {
  rowIndexClick = rowIndex;
  rowdata = row;
  loading.value = false;
  const $reportTable = proxy.$refs.reportTable;
  if ($reportTable) {
    $reportTable.setCurrentRow(row);
  }
  referForm.referList = row.referList;
  referForm.selectValue = row.selectValue;
  referForm.rptGroup = dataForm.rptGroup;
  referFormRef.value.initReferForm(referForm);
}


// 点击修改新增保存
async function handleSave() {
  if (rulesList.length === 0) {
    VxeMessage('务必先新增参考范围-----点击【新增】设置区间范围》》规则设置', VxeNotifyType.error);
    return;
  }
  saveLoading.value = true;
  // 获取表格实例
  const $Xtable = reportTable.value;
  if ($Xtable) {
    // 表格实例表用该方法拿到有id的为修改
    const updateRecords = await $Xtable.getUpdateRecords().filter((item) => item.id !== '');

    // 拿到列表中id为空的为新增
    const InsertRecords = rulesList.filter((item) => item.id === '');

    // 遍历发起请求  将筛选出有id的每一个对象（修改过的） 作为参数传递给后端
    updateRecords.forEach((e: any) => {
      let itemDictReferAddParam = e;
      proxy.$http
        .post('/api/pub/editReportRuleList', itemDictReferAddParam)
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage('修改成功', VxeNotifyType.success);
          } else {
            return;
          }
        })
        .catch((err: any) => {
          VxeMessage('修改异常', VxeNotifyType.error);
        });
    });

    //新增规则
    InsertRecords.forEach((e: any) => {
      proxy.$http
        .post('/api/pub/addReportRuleList', e)
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage('创建成功', VxeNotifyType.success);
          } else {
            return;
          }
        })
        .catch((err: any) => {
          VxeMessage('创建异常', VxeNotifyType.error);
        });
    });
    setTimeout(() => {
      findReportRulesSpecial();
      saveLoading.value = false;
    }, 500);

    saveLoading.value = false;
  } else {
    return;
  }
}

// 删除
function handleDelete() {
  const arr = reportTable.value?.getCheckboxRecords(true);
  // const sltTemplates = (proxy.$refs.templateTableRef as any).getCheckboxRecords();
  if (!(arr && arr.length > 0 && arr[0])) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    // const newNameArr = [];
    // arr.forEach((itm) => {
    //   if (itm.isSysAtt) {
    //     newNameArr.push(itm.nodeName);
    //   }
    // });
    // let node = newNameArr.join(',');
    // // console.log('node===>', node);
    // if (!isEmpty(node)) {
    //   VxeMessage('节点[' + node + ']是系统节点不允许删除', VxeNotifyType.info);
    //   return
    // }
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        const data = { reportRulesList: arr };
        const url = '/api/pub/deleteReportRuleList';
        proxy.$http
          .post(url, data)
          .then((res: any) => {
            VxeMessage(res.status.msg, VxeNotifyType.success);
            findReportRulesSpecial();
          })
          .catch((err: any) => {
            VxeMessage(err, VxeNotifyType.error);
          });
      })
      .catch((err: any) => {
        //VxeMessage(err, VxeNotifyType.error);
      });
  }
}

//组件选中事件
function SelectRowClick(e, index) {
  if (!IsEmpty(e)) {
    rulesList[index].reportId = e.id;
    rulesList[index].reportCode = e.code;
    rulesList[index].reportName = e.name;
  }
}


</script>

<style lang="scss" scoped>
#ReportRulesSpecial {
  width: 100%;
  height: 100%;

  .horizontalLine {
    // 面包屑40px  上下间距10px
    height: 100%;
    background-color: $base-white;
    padding: 0 !important;

    .button-blue,
    .button-red {
      margin: 5px 0 5px 5px;
    }
    .tableBox {
      height: calc(100% - 40px);
    }
  }
}
</style>
